package com.zf.yichat.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.service.Sms2Service;
import com.zf.yichat.service.config.ConfigSet;
import com.zf.yichat.service.config.RedisService;
import com.zf.yichat.utils.common.OKHttpUtil;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import okhttp3.Response;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * 一句话描述功能
 *
 * @author fengsong
 * @date create in 16:52 2019/6/10 2019
 */
@Service
public class Sms2ServiceImpl implements Sms2Service {

    @Autowired
    private RedisService redisService;

    @Autowired
    private ConfigSet configSet;
    private static Logger logger = LoggerFactory.getLogger(Sms2ServiceImpl.class);

    private final static String thirdBaseUrl = "https://sms.dotfire.cn/api/";

    private JSONObject httpThirdApi(String url, JSONObject body, String method) {
        String sign = redisService.getVal("third_sign");
        if (Objects.isNull(sign)) {
            JSONObject signParam = new JSONObject();
            signParam.put("access_key", configSet.getDotfire_key());
            signParam.put("access_secret", configSet.getDotfire_secret());
            signParam.put("expired_at", System.currentTimeMillis() / 1000 + 24 * 60 * 60);
            JSONObject signJson = getRightJson(thirdBaseUrl + "auth", signParam, null, "post");
            boolean success = signJson.getBoolean("success");
            if (success) {
                JSONObject msg = signJson.getJSONObject("msg");
                sign = msg.getString("token");
                redisService.setVal("third_sign", sign, 23 * 60 * 60);
            } else {
                logger.error("sms2 err:{}", signJson.toJSONString());
                throw new RuntimeException("短信请求错误");
            }
        }

        body.put("token", sign);
        return getRightJson(url, body, null, method);
    }

    private JSONObject getRightJson(String url, JSONObject body, Map header, String method) {
        try {
            String json = new JSONObject().toJSONString();
            if (Objects.nonNull(body)) {
                json = body.toJSONString();
            }
            Response response = OKHttpUtil.httpPostJsonResponse(url, json, header, method);
            JSONObject res = JSONObject.parseObject(response.body().string());
            if (response.code() == HttpStatus.SC_OK) {
                return res;
            } else {
                throw new RuntimeException("请求错误：" + response.code() + "-" + res.getString("err_msg"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("api服务器异常：" + e.getMessage());
        }
    }

//    public static void main(String[] args) {
//        try {
//            sms3("123456","18054647852");
//        } catch (UnsupportedEncodingException e) {
//            throw new RuntimeException(e);
//        } catch (NoSuchAlgorithmException e) {
//            throw new RuntimeException(e);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//    }
    public   String  sms3(String code,String mobile) throws UnsupportedEncodingException, NoSuchAlgorithmException, InterruptedException {

        String url="http://118.31.174.89:8088/v2sms.aspx";
        StringBuilder sb = new StringBuilder();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String content = "【和讯】"+"您的验证码为"+code+",请在5分钟内输入使用。超时请重新申请";
        String timestamp = sdf.format(new Date());
        String rt="json";
        String sign = Testmd5("231009bo12"+"wzfanyiran0212!"+timestamp);
        System.out.println(sign);
        sb.append("userid="+"531");
        sb.append("&content="+new String(content.getBytes(), "UTF-8"));
        sb.append("&mobile="+mobile);
        sb.append("&timestamp="+timestamp);
        sb.append("&action="+"send");
        sb.append("&sign="+sign);
        if(rt=="json")
        {
            sb.append("&rt=json");
        }
        String reString = sendPostFormUrl(url, sb.toString());

        return reString;
    }

    private   String Testmd5(String param) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] md5Byte = md5.digest(param.getBytes("utf8"));
        String result = byteToHex(md5Byte);
        return result;
    }
    private   String byteToHex(byte[] md5Byte) {
        String result = "";
        StringBuilder sb = new StringBuilder();
        for(byte each : md5Byte){
            int value = each&0xff;
            String hex = Integer.toHexString(value);
            if(value<16){
                sb.append("0");
            }
            sb.append(hex);
        }
        result = sb.toString();
        return result;
    }
    public static String sendPostFormUrl(String url, String param) {
        System.out.println("sendData:" + param);
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺�
            URLConnection conn = realUrl.openConnection();
            // 璁剧疆閫氱敤鐨勮姹傚睘鎬�
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 鍙戦�丳OST璇锋眰蹇呴』璁剧疆濡備笅涓よ
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //conn.setRequestProperty("Content-Type", "application/json");

            // 鑾峰彇URLConnection瀵硅薄瀵瑰簲鐨勮緭鍑烘祦
            out = new PrintWriter(conn.getOutputStream());
            // 鍙戦�佽姹傚弬鏁�
            out.print(param);
            // flush杈撳嚭娴佺殑缂撳啿
            out.flush();
            // 瀹氫箟BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴�
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));


            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("Exception:" + e);
            e.printStackTrace();
        }
        //浣跨敤finally鍧楁潵鍏抽棴杈撳嚭娴併�佽緭鍏ユ祦
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
         return result;

    }



    @Override
    public JSONObject sendSms(String phone, String smsCode) {
        JSONObject resJson=new JSONObject();
        try {
         String result=  sms3(smsCode,phone);
            resJson=JSONObject.parseObject(result);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }






//        JSONObject body = new JSONObject();
//        JSONArray phones = new JSONArray();
//        JSONObject codeJson = new JSONObject();
//        codeJson.put("code", smsCode);
//        phones.add(phone);
//        body.put("template_id", configSet.getDotfire_template_id());
//        body.put("phones", phones);
//        body.put("datas", codeJson);
        return resJson;
    }
}
